/**
 * @Title: FileTableController.java
 * @Copyright (C) 2017 龙图软件
 * @Description:
 * @Revision History:
 * @Revision 1.0 2017-12-6  yuanchunci
 */
 

package com.ycc.fileTransfer.controller;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ycc.fileTransfer.entity.FileTable;
import com.ycc.fileTransfer.service.FileTableService;
import com.ycc.uitl.ThumbnailUitl;

/**
 * @ClassName: FileTableController
 * @Description: Description of this class
 * @author <a href="mailto:XXX@qq.com">yuanchunci</a>于 2017-12-6 下午4:51:24
 */
@Controller
@RequestMapping(value="filetable")
public class FileTableController {
	@Resource
	FileTableService filetableService;
	
	@RequestMapping(value="/download" ,method=RequestMethod.GET)
	public void  download(HttpServletRequest request, HttpServletResponse response) throws Exception{
		Map param=new HashMap();
		param.put("id", request.getParameter("id"));
		List<FileTable> ls=filetableService.get(param);
		
		response.setContentType("application/octet-stream");
//		response.setHeader("Content-Length", "" + ls.get(0).getContent().length);
		String typesStr="mpg,mpeg,avi,rm,rmvb,mov,wmv,asf,dat(VCD),asx,wvx,mpe,mpa,mp4,mp3";
		String type= Arrays.toString(ImageIO.getReaderFormatNames())+typesStr;
		String suffix=null;
		String fileName=ls.get(0).getFilename();
		File file=null;
		if(fileName.indexOf(".") > -1) {
		      suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
		   }
		file=new File(ls.get(0).getFilepath()+"\\"+ls.get(0).getID()+ls.get(0).getFilename());
		InputStream input = new FileInputStream(file);
		byte[] byt = new byte[input.available()];
		InputStream fis = new ByteArrayInputStream(byt);
		response.setContentLength(fis.available());
		response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(ls.get(0).getFilename(), "UTF-8"));
	        // 读取要下载的文件，保存到文件输入流
        OutputStream toClient = response.getOutputStream();
		byte[] buffer = new byte[fis.available()];
		int len = 0;
	    // 循环将输入流中的内容读取到缓冲区当中
	   while ((len = fis.read(buffer)) > 0) {
	        // 输出缓冲区的内容到浏览器，实现文件下载
		   toClient.write(buffer, 0, len);
	   }
	   // 关闭文件输入流
       fis.close();
       // 关闭输出流
       toClient.close();
		
    }  
	
	 @RequestMapping(value="/urlUpload" ,method=RequestMethod.GET)
	 public String urlUpload(HttpServletRequest request,HttpServletResponse response) throws Exception{
		response.setHeader("Access-Control-Allow-Origin", "*");
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String filePath=request.getParameter("filePath");
        System.out.println(filePath);
        String uploadPath="";
        File file=new File(filePath);
		//读取配置文件
 	  Properties pro = new Properties();
 	  InputStream in = this.getClass().getResourceAsStream("/uploadLocation.properties");
	   try {
	        pro.load(in);
	 	} catch (IOException e) {
	 		e.printStackTrace();
	 	}finally{
	 		in.close();
	 	}
        if(pro!=null){
          uploadPath=pro.getProperty("uploadUrl");
          System.out.println(uploadPath);
        }
        File fileDir = new File(uploadPath);
        if(!fileDir.exists()){
        	fileDir.mkdir();
        }
    	if(file.exists()) {  
	        Map p=new HashMap();
			p.put("id", uuid);
			p.put("filepath", uploadPath);//thumbnailpath
			p.put("filename",file.getName());
			Map result=ThumbnailUitl.thumbnail(request,file,uploadPath, uploadPath,uuid);
			if(result.get("url") != null){
				p.put("thumbnailname", result.get("url"));	
			}else{
				p.put("thumbnailname", file.getName().substring(0, file.getName().indexOf("."))+".jpg");
			}
			p.put("thumbnailpath", result.get("uploadPath")+"/thum");
			filetableService.insertOne(p);
	   }
        
        System.out.println(file);
        System.out.println(filePath);
		return "redirect:showTest.html";    
    	
    }
	 
	 @RequestMapping(value="/test" ,method=RequestMethod.GET)
	 public String test(HttpServletRequest request) throws Exception{
		 return "test/test";    
    	
    }
  @RequestMapping(value="/showTest" ,method=RequestMethod.GET)
	public String showTest(HttpServletRequest request, HttpServletResponse response) throws Exception{
		Map p=new HashMap();
		List<FileTable> ls=filetableService.get(p);
		request.setAttribute("ls",  JSONArray.fromObject(ls));
		return "/file/showTest";    
	}
  @RequestMapping(value="/showImgeTest" ,method=RequestMethod.GET)
	public void showImgeTest(HttpServletRequest request, HttpServletResponse response) throws Exception{
		    Map param=new HashMap();
		    param.put("id", request.getParameter("id"));
		    List<FileTable> ls=filetableService.get(param);
		    response.setHeader("Pragma", "no-cache");
	        response.setHeader("Cache-Control", "no-cache");
	        response.setDateHeader("Expires", 0);
	        response.setContentType("image/png");
			ServletOutputStream sos = response.getOutputStream();
			String typesStr="mpg,mpeg,avi,rm,rmvb,mov,wmv,asf,dat(VCD),asx,wvx,mpe,mpa,mp4,mp3";
			String type= Arrays.toString(ImageIO.getReaderFormatNames())+typesStr;
			String suffix=null;
			if(ls.size()>0){
				String fileName=ls.get(0).getFilename();
				File file=null;
				if(fileName.indexOf(".") > -1) {
				      suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
				   }
				if(type.indexOf(suffix)>-1){
				    file=new File(ls.get(0).getThumbnailpath()+"\\"+ls.get(0).getID()+ls.get(0).getThumbnailname());
				}else{
				    file=new File(ls.get(0).getThumbnailname());
				}
				InputStream input = new FileInputStream(file);
				byte[] byt = new byte[input.available()];
				input.read(byt);
			    // 将图像输出到Servlet输出流中。
				sos.write(byt, 0, byt.length);
				sos.flush();
				sos.close();
			}
			
	}
  
	@RequestMapping(value="/delete" ,method=RequestMethod.GET)
	@ResponseBody
	public String  deleteTest(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String id=request.getParameter("id");
		int i=filetableService.delete(id);
		System.out.println(i);
		return id;
  }  
}
